package protobuf;

import java.io.IOException;
import java.io.InputStream;
import protobuf.Buffers.*;


import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.UUID;

import generic.ConnectionHandler;

public class ProtoBufHandler extends ConnectionHandler {

	@Override
	public void run() {
		try {
			// First, grab the Request from the Socket
			InputStream in = this.socket.getInputStream();
			OutputStream out = this.socket.getOutputStream();
			
			while(true){
				Request request = Request.parseDelimitedFrom(in);
				
				long numReadings = 0;

				numReadings = request.getNumReadings();
				
				long curTime = System.currentTimeMillis() - (System.currentTimeMillis() % (1000 * 60 * 15));
				long curEnergy = 5; 

				MeterReadings.Builder mrBuilder = MeterReadings.newBuilder();
				for(int i = 0; i < numReadings; i++){
					curTime+= 1000 * 60 * 15;
					curEnergy += Math.random() * 2; // KWH
					Reading r = Reading.newBuilder().setDate(curTime).setEnergy(curEnergy).setMeterid((int)(UUID.randomUUID().getLeastSignificantBits())).setPower(Math.random() * 800 + 200).build();
					//Reading r = Reading.newBuilder().setDate(new Date(curTime).getTime()).setEnergy(curEnergy).setEnergyUnit(EnergyUnit.KILOWATTHOURS).setInterval(Interval.FIFTEEN_MINUTE).setPower(Math.random() * 800 + 200).setPowerUnit(PowerUnit.WATT).build();
					mrBuilder.addReadings(r);
				}
				mrBuilder.build().writeDelimitedTo(out);
				out.flush();
				
				//System.out.println("Response written");
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
